using System;
using Microsoft.SPOT;
using Gadgeteer.Interfaces;

namespace Gadgeteer.Interfaces.Fakes.Framework
{
    public abstract class SensorBase : ThreadAction, ISensor
    {
        private double numberOfSecondsDelay;
        private double numberOfSecondsBetweenMeasurements;

        protected SensorBase(string name, double numberOfSecondsDelay,
            double numberOfSecondsBetweenMeasurements)
            : base(name)
        {
            this.numberOfSecondsDelay = numberOfSecondsDelay;
            this.numberOfSecondsBetweenMeasurements = numberOfSecondsBetweenMeasurements;

            base.Start();
        }

        private DateTime next = DateTime.MinValue;
        public void RequestMeasurement()
        {
            if (continous == false)
            {
                next = DateTime.Now.AddSeconds(numberOfSecondsDelay);
            }
        }

        protected override void Act()
        {
            if (continous)
            {
                next = DateTime.Now.AddSeconds(numberOfSecondsBetweenMeasurements);
            }
            else
            {
                next = DateTime.MinValue;
            }               

            CreateMeasurement();
        }

        protected override bool ActionRequired()
        {
            if (next > DateTime.MinValue && next < DateTime.Now)
            {
                return true;
            }

            return false;
        }

        protected abstract void CreateMeasurement();

        private bool continous = false;
        public void StartContinuousMeasurements()
        {
            continous = true;
            next = DateTime.Now.AddSeconds(numberOfSecondsDelay);
        }

        public void StopContinuousMeasurements()
        {
            continous = false;
            next = DateTime.MinValue;
        }
    }
}
